package com.web_bloks.template.client;

/**
 * Simple String Templating engine
 * Variables in the template:  $var
 * 
 * @author Jean-Lou Dupont
 *
 * <b>Usage:</b>
 * 
 * <code>
 *  String tpl = new String("some template text with a ${var}");
 *  
 * </code>
 */
public class StringTemplate {

	/**
	 * Keep a local copy.
	 * Good for reuse & performance
	 */
	String tpl = null;
	
	String result = null;
	
	public StringTemplate(String tpl) {
		this.tpl = new String( tpl );
		
		//TODO compilation
	}

	public String getResult() {
		return this.result;
	}
	
	public String substitute(ITemplateParam param) {
		
		this.result = new String( this.tpl );
		
		this.substitute(param.getKey(), param.toStringValue());
		
		return this.result;
	}
	
	/**
	 * Performs parameter substitution
	 * 
	 * @param params
	 * @return String
	 */
	public String substitute(ITemplateParam[] params) {
	
		this.result = new String( this.tpl );
		
		if (null==params)
			return getResult();
		
		for (int i=0;i<params.length;i++) {
		
			this.substitute( params[i].getKey(), params[i].toStringValue() );
		}
		
		return this.result;
	}
	
	/**
	 * Substitutes one param in the source template
	 * @param param
	 */
	protected void substitute(String param, String value) {
		this.result = this.result.replaceAll( this.buildRegexKey(param), value);
	}
	
	/**
	 * Builds the target key
	 * 
	 * @param param
	 * @return key
	 */
	public String buildRegexKey(String param) {
	
		return new String( "\\$\\{"+param.toLowerCase()+"\\}" );
		
	}
	
}//